/**
 * Created by Darius Wang on 2020/7/6.
 * 正弦曲线公式：y = A sin(Bx + C) + D
 *
 * A 控制振幅，A 值越大，波峰和波谷越大，A 值越小，波峰和波谷越小；
 * B 值会影响周期，B 值越大，那么周期越短，B 值越小，周期越长;
 * C 值会影响图像左右移动，C 值为正数，图像左移，C 值为负数，图像右移;
 * D 值控制上下移动。
 */

function delay(ms) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(1)
    }, ms)
  })
}

const cvs = document.getElementById("canvas");
const ctx = cvs.getContext("2d");

function drawWave(opts = { width: 600, a: 10, b: 0.1, amplitude: 1 }) {
  ctx.save()
  ctx.beginPath()
  ctx.strokeStyle = '#fff'
  const { width, a, b, amplitude } = opts;
  for (let x = 0; x < width; x++) {
    if (x == 0) {
      ctx.moveTo(0, 100);
    }
    let y = a * Math.sin(b * x) * amplitude;
    // setTimeout(() => {
    //   ctx.lineTo(x, y + 100);
    //   ctx.stroke();
    // }, 10 * x)
    ctx.lineTo(x, y + 100);
    ctx.stroke();
  }
}
// drawWave();

function drawMusicWave(opt = { a: 50, b: 0.1 }) {
  const { a, b } = opt
  const width = 600
  const xSpeed = 0
  ctx.beginPath()
  ctx.strokeStyle = '#fff'

  for (let x = 0; x < width; x++) {
    this.delay(10 * x).then(() => {
      let radians = x / width * Math.PI * 2
      let scale = (Math.sin(radians - Math.PI * 0.5) + 1) * 0.5
      let y = Math.sin(x * b + xSpeed) * a * scale
      console.log('radians,scale,x,y:', radians, scale, x, y)
      ctx.lineTo(x, y + 100);
      ctx.stroke();
    })
  }
  // ctx.clearRect(0, 0, 600, 600);
}

// drawMusicWave({ a: 50, b: 0.06 });
// drawMusicWave({ a: 40, b: 0.09 });
// drawMusicWave({ a: 30, b: 0.12 });
// drawMusicWave({ a: 20, b: 0.2 });

